import express, { Request, Response } from "express";
import multer from 'multer'
import { v4 as uuid } from 'uuid'
import path from 'path'
import {tokenParams} from "../../global";
import {changeProfileService} from "../service/uploadService";
import {parseToken} from "../utils/jwt";
import {fileItemAddService} from "../service/fileService";
import {flowAddService} from "../service/flowService";
import {addRecentlyService} from "../service/recentlyService";
const router = express.Router()

// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname, `../public${req.url}`)) // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
        const suffix = file.originalname.split('.')[file.originalname.split('.').length - 1]
        cb(null, `${uuid()}.${suffix}`)
    }
})


const upload = multer({ storage: storage });
// 头像上传
router.post('/profile', upload.single('file'), async (req: Request, res: Response) => {
    const file = req.file
    const url = req.url
    const { oldPath } = req.body
    const params = parseToken(req.headers[process.env.NODE_MANAGE_TOKEN as string] as string) as tokenParams
    await changeProfileService(res, `${url}/${file?.filename}`, (params as tokenParams).email, oldPath)
})

// 上传文件
router.post('/file', upload.single('file'), async (req: Request, res: Response) => {
    if (req.file) {
        const { mimetype, filename, size } = req.file
        const url = req.url
        const { parentFileUID, state, fileName } = req.body
        await fileItemAddService(res, parentFileUID, fileName, mimetype, size, `${url}/${filename}`, req.headers[process.env.NODE_MANAGE_TOKEN as string] as string, state)
    }
})

// 生成流程图JSON文件
router.post('/flow', upload.single('file'), async (req: Request, res: Response) => {
    if (req.file) {
        const { filename } = req.file
        const url = req.url
        const { name, describe } = req.body
        await flowAddService(res, `${url}/${filename}`, name, describe, req.headers[process.env.NODE_MANAGE_TOKEN as string] as string)
    }
})
//
router.post('/recently', upload.single('file'), async (req: Request, res: Response) => {
    if (req.file) {
        const { filename } = req.file
        const url = req.url
        const { name, describe } = req.body
        res.send({ code: 200, message: '成功', data: { fileURL: `${url}/${filename}` } })
    }
})

export default router